package com._119yn.host.gst200.cansocket.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class LineDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            if (msg instanceof ByteBuf buf) {
                String s = buf.toString(io.netty.util.CharsetUtil.UTF_8);
                String[] lines = s.replace("\t\n", "\n").split("\n");
                for (String line : lines) {
                    ctx.fireChannelRead(line);
                }
            } else {
                ctx.fireChannelRead(msg);
            }
        } finally {
            // ByteBuf 使用后需要释放，避免内存泄漏
            io.netty.util.ReferenceCountUtil.release(msg);
        }
    }

}
